import os
from werkzeug.datastructures import CombinedMultiDict
from flask import render_template, views, request, send_from_directory, jsonify, redirect, url_for
from sqlalchemy.exc import SQLAlchemyError
from apps.cates.models import GoodsCategory
from apps.cates.forms import GoodsCategoryForm
from apps.cates import cates_bp
from exts import db
from apps.common import func


class GoodsCategoryView(views.MethodView):
    def get(self):
        page = request.args.get('page', 1, type=int)
        pagination = GoodsCategory.query.paginate(page=page, per_page=10, error_out=False)
        cates = pagination.items
        return render_template('shop/cates/index.html', cates=cates, pagination=pagination)


cates_bp.add_url_rule('/index', view_func=GoodsCategoryView.as_view('index'))


class ImageView(views.MethodView):
    def get(self):
        base_dir = os.path.abspath(os.path.dirname('media'))
        filepath = os.path.join(base_dir, 'media')
        filename = request.args.get('filename')
        return send_from_directory(filepath, filename)


cates_bp.add_url_rule('/show', view_func=ImageView.as_view('show'))


class GoodsCategoryAddView(views.MethodView):
    def __init__(self):
        self.alist = {}

    def binddata(self, id, n):
        datas = GoodsCategory.query.filter_by(parent_id=id)
        for data in datas:
            self.alist[data.cat_id] = self.spacelength(n) + data.name
            self.binddata(data.cat_id, n + 2)
        return self.alist

    def spacelength(self, i):
        space = ''
        for j in range(1, i):
            space += '&nbsp;&nbsp;'
        return space + "|--"

    def get(self):
        form_obj = GoodsCategoryForm()
        cates = self.binddata(0, 1)
        form_obj.parent_id.choices = cates
        return render_template('shop/cates/add.html', cates=cates, form_obj=form_obj)

    def post(self):
        cates = self.binddata(0, 1)
        f = GoodsCategoryForm(CombinedMultiDict([request.files, request.form]))
        if f.validate_on_submit():
            name = request.form.get('name', '')
            cate_obj = GoodsCategory.query.filter_by(name=name).first()
            if cate_obj:
                info = '分类名称已存在'
                return render_template('shop/cates/add.html', cates=cates, form_obj=f, info=info)
            else:
                try:
                    cate = GoodsCategory()
                    cate.name = f.name.data
                    cate.parent_id = f.parent_id.data
                    file = f.logo.data
                    if file:
                        base_dir = os.path.abspath(os.path.dirname('media'))
                        filepath = os.path.join(base_dir, 'media')
                        file.save(os.path.join(filepath, file.filename))
                        cate.logo = file.filename
                    cate.sort = f.sort.data
                    db.session.add(cate)
                    db.session.commit()
                except SQLAlchemyError as e:
                    print('error')
                    db.session.rollback()
                    return render_template('shop/cates/add.html', cates=cates, form_obj=f, info='error')
                return redirect(url_for('cates.index'))
        else:
            errors = f.errors
            return render_template('shop/cates/add.html', form_obj=f, cates=cates, info=errors)


cates_bp.add_url_rule('/add', view_func=GoodsCategoryAddView.as_view('add'))


class GoodsCategoryEditView(views.MethodView):
    def get(self):
        cat_id = request.values.get('cat_id')
        cate_obj = GoodsCategory.query.filter_by(cat_id=cat_id).first()
        form_obj = GoodsCategoryForm()
        form_obj.name.data = cate_obj.name
        form_obj.sort.data = cate_obj.sort
        form_obj.logo.data = cate_obj.logo
        # form_obj.parent_id.data = cate_obj.parent_id
        cates = func.binddata(0, 1)
        form_obj.parent_id.choices = cates
        return render_template('shop/cates/edit.html', cates=cates, form_obj=form_obj, cate=cate_obj)

    def post(self):
        cates = func.binddata(0, 1)
        f = GoodsCategoryForm(CombinedMultiDict([request.files, request.form]))
        if f.validate_on_submit():
            try:
                cat_id = request.values.get('cat_id')
                cate = GoodsCategory.query.filter_by(cat_id=cat_id).first()
                cate.name = f.name.data
                cate.parent_id = f.parent_id.data
                file = f.logo.data
                if file:
                    base_dir = os.path.abspath(os.path.dirname('media'))
                    filepath = os.path.join(base_dir, 'media')
                    file.save(os.path.join(filepath, file.filename))
                    cate.logo = file.filename
                cate.sort = f.sort.data
                db.session.commit()
                return redirect(url_for('cates.index'))
            except SQLAlchemyError as e:
                print('error')
                db.session.rollback()
                return render_template('shop/cates/edit.html', cates=cates, form_obj=f, info='error')

        else:
            errors = f.errors
            return render_template('shop/cates/edit.html', form_obj=f, cates=cates, info=errors)


cates_bp.add_url_rule('/edit', view_func=GoodsCategoryEditView.as_view('edit'))

class GoodsCategoryDelView(views.MethodView):
    def post(self):
        cat_id = request.values.get('cat_id', '')
        db.session.query(GoodsCategory).filter(GoodsCategory.cat_id == cat_id).delete()
        db.session.commit()
        data = {'code': 200, 'msg': '删除成功'}
        return jsonify(data)


cates_bp.add_url_rule('/del', view_func=GoodsCategoryDelView.as_view('del'))
